import request from '@/utils/request'
import { ApiModulesRoutes } from '@/consts.js'

export function getRouters(requestSourceEnum) {
  return request({
    url: `${ApiModulesRoutes.USER}/menu/getUserMenuList`,
    method: 'GET',
    params: { requestSourceEnum }
  })
}

/**
 * 设定要登录的场景
 * @param {string} sceneId 场景id
 * @return {Promise<AxiosResponse<any>>}
 */
export async function apiBindSceneId(sceneId) {
  const url = ApiModulesRoutes.USER + '/user/bindSceneId'
  return await request.get(url, { params: { sceneId } })
}

const ROOT_ROUTE_PARAM = '0'

/**
 *  路由表 List 转换成 tree
 * @param {Array} currentRoutes 本地路由
 * @param {Array} asyncRoutes 服务端路由
 */

export function generatedMenu(currentRoutes, asyncRoutes) {
  const result = []
  const map = {}

  let listCurrentRouter = []

  currentRoutes.forEach(item => {
    listCurrentRouter = [...listCurrentRouter, item, ...routesTreeToList(item)]
  })

  asyncRoutes.forEach(item => {
    const { id, pid } = item

    !map[id] && (map[id] = { children: [] })

    map[id] = { ...item, children: map[id]['children'] }

    const treeItem = map[id]

    const find = listCurrentRouter.find(route => route.path === treeItem.path || route.path === treeItem.path.substr(1))

    let meta = find && find.meta ? { ...find.meta } : {}
    meta = { ...meta, title: treeItem.name, subTitle: treeItem.subName }

    if (pid === ROOT_ROUTE_PARAM) {
      if (find && find.showLocalRoute) {
        const currendFind = currentRoutes.find(item => item.path === treeItem.path)
        result.push({ ...treeItem, ...currendFind })
      } else {
        result.push({ ...find, ...treeItem, meta })
      }
    } else {
      if (!map[pid]) {
        map[pid] = { children: [] }
      }

      map[pid].children.push({ ...find, ...treeItem, meta })
    }
  })

  return result
}

function routesTreeToList(route) {
  if (!route || !route.children || !route.children.length) return [route]
  let result = []
  route.children.forEach(item => {
    result = [...result, ...routesTreeToList(item)]
  })
  return result
}
